package demo.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/returnValue")
public class ReturnValueController {
    @RequestMapping("view-name")
    public String viewName(Model model) {
        String tip = "控制器通过返回视图名，来指定显示哪个视图（jsp）文件";
        model.addAttribute("tip", tip);
        String msg = "返回：controller/parameter";
        model.addAttribute("msg", msg);
        return "controller/parameter";
    }

    @RequestMapping("string")
    @ResponseBody
    public String string() {
        return "普通字符串";
    }

    @RequestMapping("json1")
    @ResponseBody
    public College json() {
        return new College("01", "计算机科学与技术");
    }

    @RequestMapping("json2")
    public ResponseEntity<College> getImageAsResponseEntity() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        College c = new College("02", "网络安全");
        ResponseEntity<College> responseEntity = new ResponseEntity<>(c, headers, HttpStatus.OK);
        return responseEntity;
    }

    @RequestMapping("file")
    public ResponseEntity<byte[]> download() throws UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        byte[] data = "模拟下载文件".getBytes("UTF8");
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(data, headers, HttpStatus.OK);
        return responseEntity;
    }

    // 重定向到json
    @RequestMapping("redirect")
    public String redirect() {
        return "redirect:json1";
    }

    // 重定向到json
    @RequestMapping("redirect2")
    public View redirect2() {
        return new RedirectView("json1", true);
    }
}
